package com.example.myapplication1;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import android.graphics.Color;
import android.view.Window;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;

import com.example.myapplication1.db.DatabaseHelper;
import com.example.myapplication1.utils.PreferenceManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputLayout;
import com.google.android.material.textfield.TextInputEditText;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private TextInputLayout usernameLayout;
    private TextInputLayout passwordLayout;
    private TextInputEditText usernameInput;
    private TextInputEditText passwordInput;
    private MaterialButton loginButton;
    private View registerText;
    private View loadingProgress;
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 设置状态栏
        setupStatusBar();
        
        setContentView(R.layout.activity_login);

        // Initialize database
        databaseHelper = new DatabaseHelper(this);
        if (!databaseHelper.isDatabaseExists()) {
            Log.d(TAG, "Creating new database");
            databaseHelper.getWritableDatabase();
        }

        preferenceManager = new PreferenceManager(this);

        // 检查是否已登录
        if (preferenceManager.isLoggedIn()) {
            startMainActivity();
            return;
        }

        initViews();
        setupClickListeners();

        // 检查是否从注册页面传来用户名
        String registeredUsername = getIntent().getStringExtra("username");
        if (registeredUsername != null && !registeredUsername.isEmpty()) {
            usernameInput.setText(registeredUsername);
            passwordInput.requestFocus(); // 自动聚焦到密码输入框
            Toast.makeText(this, "请使用新注册的账号登录", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }

    private void setupStatusBar() {
        // 设置状态栏为透明
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.primary_dark, null));
        
        // 设置状态栏图标为深色
        WindowInsetsControllerCompat windowInsetsController =
                WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
        windowInsetsController.setAppearanceLightStatusBars(true);
    }

    private void initViews() {
        usernameLayout = findViewById(R.id.usernameLayout);
        passwordLayout = findViewById(R.id.passwordLayout);
        usernameInput = findViewById(R.id.usernameInput);
        passwordInput = findViewById(R.id.passwordInput);
        loginButton = findViewById(R.id.loginButton);
        registerText = findViewById(R.id.registerText);
        loadingProgress = findViewById(R.id.loadingProgress);
    }

    private void setupClickListeners() {
        loginButton.setOnClickListener(v -> attemptLogin());
        registerText.setOnClickListener(v -> startActivity(new Intent(this, RegisterActivity.class)));
        findViewById(R.id.forgotPasswordText).setOnClickListener(v -> 
            startActivity(new Intent(this, ForgotPasswordActivity.class)));
    }

    private void attemptLogin() {
        // 重置错误提示
        usernameLayout.setError(null);
        passwordLayout.setError(null);

        // 获取输入内容
        String username = usernameInput.getText().toString().trim();
        String password = passwordInput.getText().toString();

        // 验证输入
        if (!validateInput(username, password)) {
            return;
        }

        // 显示加载动画
        showLoading(true);

        try (DatabaseHelper db = new DatabaseHelper(this)) {
            if (db.checkUser(username, password)) {
                // 获取用户ID
                long userId = getUserId(username);
                if (userId != -1) {
                    // 登录成功，保存登录状态
                    preferenceManager.setLoggedIn(true);
                    preferenceManager.setUsername(username);
                    preferenceManager.setUserId(userId);

                    showLoading(false);
                    Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
                    
                    // 跳转到主界面
                    startMainActivity();
                } else {
                    showLoading(false);
                    Toast.makeText(this, R.string.error_invalid_credentials, Toast.LENGTH_SHORT).show();
                }
            } else {
                showLoading(false);
                Toast.makeText(this, R.string.error_invalid_credentials, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private long getUserId(String username) {
        try {
            return databaseHelper.getUserId(username);
        } catch (Exception e) {
            Log.e(TAG, "Error getting user ID: " + e.getMessage());
            return -1;
        }
    }

    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private boolean validateInput(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            usernameLayout.setError(getString(R.string.error_empty_username));
            return false;
        }

        if (TextUtils.isEmpty(password)) {
            passwordLayout.setError(getString(R.string.error_empty_password));
            return false;
        }

        return true;
    }

    private void showLoading(boolean show) {
        loadingProgress.setVisibility(show ? View.VISIBLE : View.GONE);
        loginButton.setEnabled(!show);
        usernameInput.setEnabled(!show);
        passwordInput.setEnabled(!show);
        registerText.setEnabled(!show);
    }
} 